<template>
  <div class="main-content-area">
    <!-- Section: page title -->
    <section class="bg-green-600 flex-col flex items-center justify-center" style="height: 10vh;text-align: center;overflow-x: auto;">
      <div class="container mx-auto px-4">
        <div class="row">
          <div class="col-md-12 text-center">
            <h4 class="font-bold text-white whitespace-nowrap" style="font-size: clamp(1.5rem, 2.5vw, 2.25rem);">Data intelligence-driven cabon management toward net-zero future</h4>
          </div>
        </div>
      </div>
    </section>

    <!-- Section: About -->
    <section class="py-16 px-36">
      <div class="container mx-auto px-4">
        <div class="section-content">
          <div class="row">
            <div class="col-lg-12 mb-12">
              <blockquote class="border-l-10 border-green-600 pl-6 bg-gray-50 p-6 rounded-r-lg">
                <p class="text-lg leading-relaxed text-gray-700">
                  {{ contactInfo.detailed || '3E is an integrated research and analysis platform dedicated to macroeconomic, energy and emission data monitoring, corporate/individual carbon emission accounting, industry carbon analysis and carbon emission reduction program planning. It is also a micro-environmental, social and governance (ESG) performance and carbon big data management and consulting service platform. With cutting-edge comprehensive assessment modeling technology, data intelligence algorithms, a strong team of experts and extensive partnerships, 3E deeply serves the green development and sustainable' }}
                </p>
              </blockquote>
            </div>
            
            <div class="grid grid-cols-1 lg:grid-cols-12 gap-8">
              <!-- 联系方式 -->
              <div class="lg:col-span-4">
                <!-- 电话 -->
                <div class="bg-gray-50 p-6 rounded-lg mb-6 flex items-center hover:shadow-lg transition-shadow">
                  <div class="w-16 h-16 bg-green-600 rounded-full flex items-center justify-center mr-4">
                    <svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
                    </svg>
                  </div>
                  <div>
                    <h5 class="text-xl font-semibold text-gray-900 mb-2">Phone</h5>
                    <div class="text-gray-700">
                      <a :href="`tel:${contactInfo.tel}`" class="hover:text-green-600 transition-colors">{{ contactInfo.tel }}</a>
                    </div>
                  </div>
                </div>

                <!-- 邮箱 -->
                <div class="bg-gray-50 p-6 rounded-lg mb-6 flex items-center hover:shadow-lg transition-shadow">
                  <div class="w-16 h-16 bg-green-600 rounded-full flex items-center justify-center mr-4">
                    <svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" d="M3 8l7.89 4.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                    </svg>
                  </div>
                  <div>
                    <h5 class="text-xl font-semibold text-gray-900 mb-2">Email</h5>
                    <div class="text-gray-700">
                      <a :href="`mailto:${contactInfo.email}`" class="hover:text-green-600 transition-colors">{{ contactInfo.email }}</a>
                    </div>
                  </div>
                </div>

                <!-- 地址 -->
                <div class="bg-gray-50 p-6 rounded-lg mb-6 flex items-center hover:shadow-lg transition-shadow">
                  <div class="w-16 h-16 bg-green-600 rounded-full flex items-center justify-center mr-4">
                    <svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                      <path stroke-linecap="round" stroke-linejoin="round" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                    </svg>
                  </div>
                  <div>
                    <h5 class="text-xl font-semibold text-gray-900 mb-2">Address</h5>
                    <div class="text-gray-700">{{ contactInfo.address }}</div>
                  </div>
                </div>
              </div>

                             <!-- 地图区域 -->
               <div class="lg:col-span-8">
                 <div class="bg-gray-200 rounded-lg overflow-hidden" style="height: 580px;">
                   <div id="map" class="w-full h-full" style="min-height: 580px;"></div>
                 </div>
               </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { contactApi } from '~/public/utils/api'

// 联系信息
const contactInfo = ref({
  tel: '4006790996',
  email: 'contacts@hongyuan3e.com',
  address: '北京市海淀区中关村东路80号',
  latitude: 39.98,
  longitude: 116.34,
  detailed: ''
})

// 获取联系信息
const fetchContactInfo = async () => {
  try {
    const result = await contactApi.getContactInfo()
    if (result.data) {
      contactInfo.value = {
        tel: result.data.tel || contactInfo.value.tel,
        email: result.data.email || contactInfo.value.email,
        address: result.data.address || contactInfo.value.address,
        latitude: result.data.latitude || contactInfo.value.latitude,
        longitude: result.data.longitude || contactInfo.value.longitude,
        detailed: result.data.detailed || contactInfo.value.detailed
      }
    }
  } catch (error) {
    console.error('Failed to fetch contact info:', error)
  }
}

// 设置页面标题
useHead({
  title: 'About Us - Carbon Tariff Platform',
  meta: [
    { name: 'description', content: 'Learn about our professional carbon tariff consulting services and commitment to smart carbon management and scientific carbon neutrality' },
    { name: 'keywords', content: 'about carbon tariff, CBAM consulting, carbon management solutions, professional team' }
  ]
})

onMounted(async () => {
  // 获取联系信息
  await fetchContactInfo()
  
  // 使用Google Maps API (英文版本)
  const loadGoogleMaps = () => {
    return new Promise((resolve, reject) => {
      if (typeof google !== 'undefined' && google.maps) {
        resolve(google)
        return
      }

      const script = document.createElement('script')
      const config = useRuntimeConfig()
      const apiKey = config.public.googleMapsApiKey

      // 检查是否有有效的API key
      const hasValidApiKey = apiKey &&
                            apiKey.trim() !== '' &&
                            apiKey !== 'your_google_maps_api_key_here' &&
                            apiKey !== '15b969252956ecd1f81dcba8'

      // 构建API URL - 添加英文语言支持
      let scriptSrc = 'https://maps.googleapis.com/maps/api/js?libraries=marker&language=en&region=US&callback=Function.prototype'

      if (hasValidApiKey) {
        scriptSrc = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&libraries=marker&language=en&region=US&callback=Function.prototype`
        console.log('🗺️ Loading Google Maps (English) with API key')
      } else {
        console.warn('🗺️ Loading Google Maps (English) in TEST MODE (will show watermark)')
        console.warn('💡 To remove watermark, set a valid GOOGLE_MAPS_API_KEY in .env file')
      }

      script.src = scriptSrc
      script.async = true
      script.onload = () => {
        console.log('✅ Google Maps (English) script loaded successfully')
        if (!hasValidApiKey) {
          console.warn('⚠️ Map will display "For development purposes only" watermark')
        }
        resolve(google)
      }
      script.onerror = () => {
        console.error('❌ Failed to load Google Maps script')
        reject(new Error('Failed to load Google Maps'))
      }
      document.head.appendChild(script)
    })
  }
  
  try {
    // 加载Google Maps API
    const google = await loadGoogleMaps()
    console.log('Google Maps loaded successfully:', google)

    // 确保地图容器存在
    const mapContainer = document.getElementById('map')
    if (!mapContainer) {
      console.error('Map container not found')
      return
    }

    console.log('Map container found:', mapContainer)

    const config = useRuntimeConfig()
    const mapId = config.public.googleMapsMapId
    const apiKey = config.public.googleMapsApiKey

    // 检查是否有有效的API key
    const hasValidApiKey = apiKey &&
                          apiKey.trim() !== '' &&
                          apiKey !== 'your_google_maps_api_key_here' &&
                          apiKey !== '15b969252956ecd1f81dcba8'

    // 地图配置 (英文界面)
    const mapOptions = {
      zoom: 16,
      center: {
        lat: contactInfo.value.latitude,
        lng: contactInfo.value.longitude
      },
      mapTypeControl: true,
      streetViewControl: true,
      fullscreenControl: true,
      zoomControl: true,
      // 确保控件显示为英文
      controlSize: 28
    }

    // 只有在有有效API key时才使用Map ID
    if (hasValidApiKey && mapId) {
      mapOptions.mapId = mapId
      console.log('🎨 Using custom Map ID:', mapId)
    } else if (!hasValidApiKey) {
      console.warn('⚠️ Map ID disabled in test mode')
    }

    // 创建地图实例
    const map = new google.maps.Map(mapContainer, mapOptions)

    console.log('🗺️ Map (English) created successfully')
    if (!hasValidApiKey) {
      console.warn('💡 To enable full features and remove watermark, configure GOOGLE_MAPS_API_KEY')
    }

    // 创建标记（兼容测试模式）
    let marker

    try {
      // 尝试使用高级标记（需要API key）
      if (hasValidApiKey) {
        const { AdvancedMarkerElement } = await google.maps.importLibrary("marker")
        marker = new AdvancedMarkerElement({
          map: map,
          position: {
            lat: contactInfo.value.latitude,
            lng: contactInfo.value.longitude
          },
          title: 'Hongyuan 3E'
        })
        console.log('✨ Using AdvancedMarkerElement')
      } else {
        throw new Error('Using fallback marker for test mode')
      }
    } catch (error) {
      // 降级到基础标记（测试模式兼容）
      marker = new google.maps.Marker({
        map: map,
        position: {
          lat: contactInfo.value.latitude,
          lng: contactInfo.value.longitude
        },
        title: 'Hongyuan 3E'
      })
      console.warn('📍 Using basic Marker (test mode or fallback)')
    }

    // 创建信息窗口 (英文内容)
    const infoWindow = new google.maps.InfoWindow({
      content: `
        <div style="padding: 12px; max-width: 280px; font-family: Arial, sans-serif;">
          <h4 style="margin: 0 0 10px 0; color: #333; font-size: 16px; font-weight: bold;">Hongyuan 3E</h4>
          <p style="margin: 0 0 6px 0; color: #666; font-size: 14px; line-height: 1.4;">
            <strong>Address:</strong><br>${contactInfo.value.address}
          </p>
          <p style="margin: 0; color: #666; font-size: 14px;">
            <strong>Phone:</strong> ${contactInfo.value.tel}
          </p>
          <p style="margin: 6px 0 0 0; color: #666; font-size: 14px;">
            <strong>Email:</strong> ${contactInfo.value.email}
          </p>
        </div>
      `
    })

    // 点击标记时打开信息窗口
    marker.addListener('click', () => {
      infoWindow.open(map, marker)
    })

    console.log('✅ Map (English) initialization completed')

  } catch (error) {
    console.error('❌ Error initializing map:', error)

    // 显示错误信息给用户 (英文)
    const mapContainer = document.getElementById('map')
    if (mapContainer) {
      const config = useRuntimeConfig()
      const apiKey = config.public.googleMapsApiKey
      const hasValidApiKey = apiKey &&
                            apiKey.trim() !== '' &&
                            apiKey !== 'your_google_maps_api_key_here' &&
                            apiKey !== '15b969252956ecd1f81dcba8'

      let errorMessage = 'Map Loading Failed'
      let errorDetail = 'Please check your network connection and try again'

      if (!hasValidApiKey) {
        errorMessage = 'Map Configuration Error'
        errorDetail = 'Please configure a valid Google Maps API key'
      }

      mapContainer.innerHTML = `
        <div style="display: flex; align-items: center; justify-content: center; height: 100%; background: #f5f5f5; color: #666; padding: 20px;">
          <div style="text-align: center; max-width: 320px; font-family: Arial, sans-serif;">
            <div style="font-size: 48px; margin-bottom: 16px;">🗺️</div>
            <p style="font-size: 16px; margin-bottom: 8px; color: #333; font-weight: 500;">${errorMessage}</p>
            <p style="font-size: 12px; color: #666; line-height: 1.4; margin-bottom: 12px;">${errorDetail}</p>
            ${!hasValidApiKey ? '<p style="font-size: 11px; color: #999; margin-top: 12px; font-style: italic;">Dev Tip: Set GOOGLE_MAPS_API_KEY in .env file</p>' : ''}
          </div>
        </div>
      `
    }
  }
})
</script>
